<template>
  <div>
    <el-card class="query-card">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>通知管理</el-breadcrumb-item>
        <el-breadcrumb-item>通知列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <el-card style="margin-top: 8px">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="标题名称">
          <el-input
            v-model="queryForm.infortitle"
            placeholder="请输入标题关键字"
            clearable
          />
        </el-form-item>
        <el-form-item label="发布人">
          <el-input
            v-model="queryForm.fbr"
            placeholder="请输入发布人关键字"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" plain @click="openAddDialog">
            发布通知
          </el-button>
          <el-button
            type="danger"
            plain
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        style="width: 100%; margin-top: 10px"
        :data="tableData"
        border
        stripe
        :loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="infortitle" label="标题名称" />
        <el-table-column prop="fbr" label="发布人" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? "开启" : "关闭" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="openEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 10px; display: flex; justify-content: flex-end">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 30, 50]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 / 修改对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'add' ? '发布通知' : '编辑通知'"
      width="60%"
      :close-on-click-modal="false"
      @closed="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="90px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题名称" prop="infortitle">
              <el-input
                v-model="formModel.infortitle"
                placeholder="请输入标题名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formModel.status">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="0">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发布人">
              <el-input v-model="publisherName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容">
          <div class="editor-wrapper">
            <div class="editor-toolbar">
             
            </div>
            <el-input
              v-model="formModel.content"
              type="textarea"
              :rows="8"
              placeholder="可填写通知内容（仅用于前端展示）"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { onMounted, reactive, ref } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";

interface InformRow {
  content: string;
  id: number;
  infortitle: string;
  status: number;
  fbr: string;
  createtime: string;
}

interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResult<T> {
  code: number;
  msg: string;
  data: T;
}

const loading = ref(false);
const tableData = ref<InformRow[]>([]);
const multipleSelection = ref<InformRow[]>([]);

const queryForm = reactive({
  infortitle: "",
  fbr: "",
});

const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  pageCount: 0,
});

const dialogVisible = ref(false);
const dialogMode = ref<"add" | "edit">("add");
const submitLoading = ref(false);
const publisherName = ref("");

const formRef = ref<FormInstance>();
const formModel = reactive({
  id: 0,
  infortitle: "",
  status: 1,
  content: "",
});

const formRules = reactive<FormRules>({
  infortitle: [{ required: true, message: "请输入标题名称", trigger: "blur" }],
});

const editorTools = [
  "A",
  "B",
  "I",
  "U",
  "H",
  "对齐",
  "列表",
  "图片",
  "链接",
  "撤销",
];

const fetchCurrentUserName = async () => {
  const userId = localStorage.getItem("userid");
  if (!userId) return;
  try {
    const { data } = await https.Reads.get("/RBAC/GetUserId", {
      params: { userid: userId },
    });
    if (data?.code === 1) {
      publisherName.value =
        data?.data?.username || data?.data?.accountname || "";
    }
  } catch (error) {
    console.error("获取当前登录人失败:", error);
  }
};

const fetchTableData = () => {
  loading.value = true;
  const params: any = {
    pageindex: pagination.pageindex,
    pagesize: pagination.pagesize,
  };
  if (queryForm.infortitle) params.infortitle = queryForm.infortitle;
  if (queryForm.fbr) params.fbr = queryForm.fbr;

  https.Reads
    .get<ApiPageingResponse<InformRow>>("/Manage/ShowInfor", { params })
    .then((res) => {
      const response = res.data;
      if (response.code === 1) {
        tableData.value = response.data || [];
        pagination.totalCount = response.totalCount || 0;
        pagination.pageCount = response.pageCount || 0;
      } else {
        tableData.value = [];
        pagination.totalCount = 0;
        pagination.pageCount = 0;
        ElMessage.error(response.msg || "获取通知列表失败");
      }
    })
    .catch((error) => {
      console.error("获取通知列表失败:", error);
      tableData.value = [];
      pagination.totalCount = 0;
      pagination.pageCount = 0;
      ElMessage.error("获取通知列表失败，请稍后再试");
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  fetchCurrentUserName();
  fetchTableData();
});

const handleQuery = () => {
  pagination.pageindex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.infortitle = "";
  queryForm.fbr = "";
  handleQuery();
};

const handleSizeChange = (val: number) => {
  pagination.pagesize = val;
  pagination.pageindex = 1;
  fetchTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.pageindex = val;
  fetchTableData();
};

const handleSelectionChange = (val: InformRow[]) => {
  multipleSelection.value = val;
};

const openAddDialog = () => {
  dialogMode.value = "add";
  dialogVisible.value = true;
  resetForm();
};

const openEditDialog = (row: InformRow) => {
  dialogMode.value = "edit";
  formModel.id = row.id;
  formModel.infortitle = row.infortitle;
  formModel.status = row.status;
  formModel.content = row.content;
  dialogVisible.value = true;
};

const resetForm = () => {
  formRef.value?.resetFields();
  formModel.id = 0;
  formModel.infortitle = "";
  formModel.status = 1;
  formModel.content = "";
};

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (!valid) return;
    if (!publisherName.value) {
      ElMessage.warning("未获取到当前登录人信息，请重新登录");
      return;
    }
    submitLoading.value = true;
    const payload = {
      infortitle: formModel.infortitle,
      status: formModel.status,
      fbr: publisherName.value,
      content:formModel.content
    };
    const request =
      dialogMode.value === "add"
        ? https.Writes.post<ApiResult<number>>("/Manage/Addnotice", payload)
        : https.Writes.put<ApiResult<number>>("/Manage/Updatenotice", {
            ...payload,
            id: formModel.id,
          });

    request
      .then((res) => {
        if (res.data.code === 1) {
          ElMessage.success(res.data.msg || "操作成功");
          dialogVisible.value = false;
          resetForm();
          fetchTableData();
        } else {
          ElMessage.error(res.data.msg || "操作失败");
        }
      })
      .catch((error) => {
        console.error("通知操作失败:", error);
        ElMessage.error("操作失败，请稍后再试");
      })
      .finally(() => {
        submitLoading.value = false;
      });
  });
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定要删除该通知吗？", "提示", {
    type: "warning",
  })
    .then(() => deleteRequest([id]))
    .catch(() => {});
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的通知");
    return;
  }
  const ids = multipleSelection.value.map((item) => item.id);
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 条通知吗？`,
    "提示",
    {
      type: "warning",
    }
  )
    .then(() => deleteRequest(ids))
    .catch(() => {});
};

const deleteRequest = (ids: number[]) => {
  https.Writes
    .delete<ApiResult<number>>("/Manage/DelAllnotice", {
      data: { ids },
    })
    .then((res) => {
      if (res.data.code === 1) {
        ElMessage.success(res.data.msg || "删除成功");
        fetchTableData();
      } else {
        ElMessage.error(res.data.msg || "删除失败");
      }
    })
    .catch((error) => {
      console.error("删除通知失败:", error);
      ElMessage.error("删除失败，请稍后再试");
    });
};

const formatDate = (val: string) => {
  if (!val) return "";
  const d = new Date(val);
  if (Number.isNaN(d.getTime())) return val;
  const pad = (n: number) => `${n}`.padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(
    d.getHours()
  )}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
</script>

<style scoped>
.query-card {
  margin-bottom: 8px;
}

.editor-wrapper {
  width: 100%;
}

.editor-toolbar {
  display: flex;
  gap: 10px;
  padding: 6px 12px;
  border: 1px solid #e4e7ed;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  color: #909399;
  flex-wrap: wrap;
}

.editor-toolbar span {
  font-size: 14px;
}
</style>

